import originJsonp from 'jsonp'

// 封装jsonp请求
export default (url, data, options) => {
  const fullUrl = url += buildQueryString(data) !== '' ? `?${buildQueryString(data)}` : ''

  return new Promise((resolve, reject) => {
    originJsonp(fullUrl, options, (err, data) => {
      if (!err) {
        resolve(data)
      } else {
        reject(err)
      }
    })
  })
}

// 构建请求url的query参数
const buildQueryString = data => {
  let queryString = ''
  for (const key in data) {
    const value = data[key] !== undefined ? data[key] : ''

    queryString += `&${key}=${encodeURIComponent(value)}`
  }

  return queryString !== '' ? queryString.substring(0) : queryString
}
